package com.example.wangyuyuan.androidframe.data.httpdata;

import android.app.Service;

import com.example.wangyuyuan.androidframe.data.api.CacheProviders;
import com.example.wangyuyuan.androidframe.data.api.Sercice;
import com.example.wangyuyuan.androidframe.data.retrofit.RetrofitUtils;
import com.example.wangyuyuan.androidframe.mvp.base.BaseResponse;
import com.example.wangyuyuan.androidframe.mvp.base.ErrorBean;
import com.example.wangyuyuan.androidframe.mvp.entitry.LoginUserinfo;
import com.example.wangyuyuan.androidframe.utils.FileUtil;

import java.io.File;
import java.util.HashMap;

import io.rx_cache.DynamicKey;
import io.rx_cache.EvictDynamicKey;
import io.rx_cache.Reply;
import io.rx_cache.internal.RxCache;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by wangyuyuan on 2017/5/9.
 */

public class HttpData extends RetrofitUtils {

    private static File cacheDirectory = FileUtil.getcacheDirectory();
    private static final CacheProviders providers = new RxCache.Builder().persistence(
            cacheDirectory).using(CacheProviders.class);
    protected static final Sercice service = getRetrofit().create(Sercice.class);


    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final HttpData INSTANCE = new HttpData();
    }

    //获取单例
    public static HttpData getInstance() {
        return SingletonHolder.INSTANCE;
    }


    /**
     * 插入观察者
     */
    public static <T> void setSubscribe(Observable<T> observable, Observer<T> observer) {
        observable.subscribeOn(Schedulers.io()).subscribeOn(Schedulers.computation())//子线程访问网络
                .observeOn(AndroidSchedulers.mainThread())//回调到主线程
                .subscribe(observer);
    }

    /**
     * 用来统一处理RxCacha的结果
     */
    private class HttpResultFuncCcche<T> implements Func1<Reply<T>, T> {
        @Override
        public T call(Reply<T> httpResult) {
            return httpResult.getData();
        }
    }

    //    登录
    public void login(Observer<LoginUserinfo> observer, String region, String phone, String password) {
        Observable observable = service.login(new LoginUserinfo(region, phone, password));
        Observable observableCache = providers.login(observable, new DynamicKey("登录"),
                new EvictDynamicKey(true)).map(new HttpResultFuncCcche<LoginUserinfo>());
        setSubscribe(observableCache, observer);
    }
}
